<?php

namespace Wxwork\Http;

class Response
{
    private $code;

    private $body;

    private $header;

    private $success = false;

    private $error;

    public function __construct($code = 500, $body = '', $header = '')
    {
        $this->code = $code;
        $this->body = $body;

        if ($this->code == 200) {
            $this->success = true;
        }
    }

    public static function generate($code, $body, $header): Response
    {
        return (new self($code, $body, $header));
    }

    public function resolve(): Response
    {
        if (json_decode($this->body, true)) {
            $this->body = json_decode($this->body, true);
        }
        $errmsg = $this->body['errmsg'] ?? '';
        if ($errmsg and $errmsg!= 'ok') {
            $this->setError($this->body['errmsg']);
        }

        return $this;
    }

    public function setCode($code): Response
    {
        $this->code = $code;
        if ($this->code == '200') {
            $this->success = true;
        }
        return $this;
    }

    public function setHeader($header): Response
    {
        $this->header = $header;
        return $this;
    }

    public function setBody($body): Response
    {
        $this->body = $body;
        return $this;
    }

    public function setError($error): Response
    {
        $this->error = $error;
        $this->success = false;
        return $this;
    }

    public function isSuccess(): bool
    {
        return $this->success == true;
    }

    public function getError()
    {
        return $this->error;
    }

    public function getBody()
    {
        return $this->body;
    }

}
